<template>
  <div class="login_box">
    <div id="ww_login">
    </div>
  </div>

</template>

<script>
import { wechatUserIdPcLogin,getInfo } from "@/api/login";
import { setToken } from '@/utils/auth'
export default {
  name: "Index",
  data() {
    return {
      // 版本号
      version: "3.8.8"
    };
  },
  mounted() {
    // 初始化登录组件
    this.weLogin();
    // console.log(this.$ww, 'ww');
    // console.log(process.env.VUE_APP_APPID, 'VUE_APP_APPID');
    // console.log(process.env.VUE_APP_BACKURL, 'BACKURL');
  },
  methods: {
    goTarget(href) {
      window.open(href, "_blank");
    },
    weLogin() {
      // this.$refs.weChatCodeLogin.appendChild(wwLogin.el);
      const self = this;
      this.$ww.createWWLoginPanel({
        el: '#ww_login',
        params: {
          login_type: 'ServiceApp',
          // agentid: '1000157',
          appid: process.env.VUE_APP_APPID,
          redirect_uri: process.env.VUE_APP_BACKURL,
          state: 'loginState',
          redirect_type: 'callback',
        },
        onCheckWeComLogin({ isWeComLogin }) {
          console.log(isWeComLogin, 'onCheckWeComLogin')
        },
        onLoginSuccess({ code }) {
          console.log({ code }, 'onLoginSuccess')
          self.codeToToken(code)
        },
        onLoginFail(err) {
          console.log(err, 'fail')
        },
      })
    },
    async codeToToken(code) {
      // console.log('进入请求');
      let res = await wechatUserIdPcLogin({ "code": code })
      if (res.code == 200) {
        //this.$router.push({path:'/home'})
        this.$store.commit('SET_TOKEN', res.token)
        setToken(res.token)
        await this.getMyinfo()
        this.$router.push({ path: this.redirect || "/" }).catch(() => { });
      }
      console.log(res, 'wechatUserIdPcLogin');
    },
    async getMyinfo() {
      const myPhone = localStorage.getItem('phonenumber') || '';
      if (myPhone) {
        localStorage.removeItem('phonenumber')
      }
      let result = await getInfo()
      if (result.code == 200) {
        const user = result.user
        localStorage.setItem('phonenumber', user.phonenumber || '')
      }
    }
  }
};
</script>

<style scoped lang="scss">
.login_box {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
</style>